package eu.horyzont.systemyrozproszone.systemmagazynowy.serwer;

import eu.horyzont.systemyrozproszone.systemmagazynowy.serwer.httplistener.HttpListener;
import eu.horyzont.systemyrozproszone.systemmagazynowy.serwer.serializer.Serializer;
import eu.horyzont.systemyrozproszone.systemmagazynowy.serwer.session.SessionImpl;
import eu.horyzont.systemyrozproszone.systemmagazynowy.serwer.session.Session;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;

/**
 * Contains various helper methods.
 * @author pawel
 */
public class Utils {
    
    private static final String SETTINGS_FILE = "settings.properties";
    private static final String JDBC_DRIVER_KEY = "jdbc.driver";
    private static final String JDBC_URL_KEY = "jdbc.url";
    private static final Logger logger = Logger.getLogger(Utils.class);
    
    private static Session session = null;
    private static Serializer serializer = null;
    private static HttpListener httpListener = null;
    
    /**
     * Gets an instance of {@link hu.netmind.beankeeper.Store}.
     * Connection settings are read from {@code settings.properties} file
     * @return a ready to work data store
     * @throws IOException 
     */
    public static Session getSession() throws IOException {
        if (session == null) {
            Properties settings = new Properties();
            ClassLoader loader = Thread.currentThread().getContextClassLoader();           
            InputStream stream = loader.getResourceAsStream(SETTINGS_FILE);
            settings.load(stream);
            
            String jdbcDriver = settings.getProperty(JDBC_DRIVER_KEY);
            String jdbcUrl = settings.getProperty(JDBC_URL_KEY);
            logger.info(String.format("Loaded settings from file '%s': { %s: '%s', %s: '%s' }", SETTINGS_FILE, JDBC_DRIVER_KEY, jdbcDriver, JDBC_URL_KEY, jdbcUrl));
            
            session = new SessionImpl(jdbcDriver, jdbcUrl);
        }
        return session;
    }

    public static Serializer getSerializer() {
        if (serializer == null) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        return serializer;
    }

    public static HttpListener getHttpListener() {
        if (httpListener == null) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
        return httpListener;
    }
    
}
